<template>
	<div>
		<div v-if="this.$route.meta.title == '搜索结果'">
			<van-nav-bar title="标题" left-text="返回" left-arrow @click-left="$router.push('/')">
				<template #title>
					<van-search v-model="searchValue" placeholder="请输入搜索关键词" @search="SearchFoods" />
				</template>
			</van-nav-bar>
			<!-- 未找到内容 -->
			<van-empty v-if="isEmpty" image="search" description="没有找到相关的菜谱哦……请重新搜索！" />
		</div>
		<FoodsClassificationList :FoodsMenuList="FoodsMenuList.datas" />
	</div>
</template>

<script>
import FoodsClassificationList from './components/FoodsClassificationList.vue';

import { setSearchHistory } from '@/utils/cache';
import { getMenuDetail } from '@/api/menu';
export default {
	name: 'FoodClassificationListIndex',
	props: {
		title: {
			type: String,
			default: '热门专题',
			require: true,
		},
	},
	watch: {
		// 监听title是否变化，如果变化重新获取数据
		async title(newVal) {
			this.FoodsMenuList = this.getMenuDetails(newVal);
		},
	},
	components: {
		FoodsClassificationList,
	},
	computed: {
		isEmpty() {
			return this.FoodsMenuList.flag == void 0;
		},
	},
	created() {
		this.getMenuDetails();
	},
	activated() {
		this.$router.push(`/FoodsClassificationList/${this.title}`);
	},
	data() {
		return {
			FoodsMenuList: [],
			searchValue: '',
		};
	},
	methods: {
		/** @method 获取菜谱详情 */
		async getMenuDetails() {
			const res = await getMenuDetail({ type: this.title });

			if (res.ret_msg) {
				this.$toast(res.ret_msg);
				return;
			} else {
				this.FoodsMenuList = res;
			}
		},
		/**
		 * @method 搜索菜谱
		 * @param {String} value 搜索关键词
		 * */
		SearchFoods(value) {
			// 判断是否为合法内容
			if (!value) {
				this.$toast('请输入搜索关键词');
				return;
			}
			// 正则判断是否为汉字
			if (!value.match(/^[\u4e00-\u9fa5]+$/)) {
				this.$toast('请输入合法内容');
				return;
			}

			// 添加搜索历史
			setSearchHistory(value);
			// 清空搜索值
			this.searchValue = '';

			this.$router.push({
				path: `/FoodClassificationLists/${value}`,
			});
		},
	},
};
</script>

<style></style>
